<template>
  <div class="container">
    <div class="card" v-loading="loading">
      <!-- 搜索项 -->
      <div
        class="switchLine flexColCenter"
        v-if="$store.getters.curRole == 'schoolAdmin'"
      >
        <div class="switchLine_left">学科专业组</div>
        <div>
          <el-switch
            @change="switchChange"
            v-model="value"
            :active-value="1"
            :inactive-value="0"
            active-color="#28b28b"
            inactive-color="#d1d1d1"
          >
          </el-switch>
        </div>
        <div class="switchLine_right">
          {{
            value == 1
              ? '注：停用后将清除所有学科专业组中的课程数据！'
              : '注：请先设置学科专业组并启用后再开启，防止教师编辑课程后无法保存！课程所属分院同学科专业组！'
          }}
        </div>
      </div>
      <div class="search_bar">
        <el-form
          @submit.native.prevent
          size="small"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="">
            <el-input
              v-model="params.disciplineGroupName"
              placeholder="请输入学科专业组"
              clearable
              @keyup.enter.native="getList"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </el-form-item>
          <el-form-item class="search_btns">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="small"
              @click="getList"
            >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetSearch"
            >重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 列表 -->
      <div
        class="list"
        v-if="tableData.length > 0"
      >
        <!-- 学院-专业组列表 -->
        <div class="branchItem" v-for="(item, index) in tableData" :key="index">
          <!-- 学院名称 -->
          <div class="branchItem_line flexBet flexColCenter">
            <div class="branchName flexColCenter">
              {{ item.branchName }}
              <div class="up" v-if="index != 0">
                <img
                  @click="branchSort(item, index, 'up')"
                  class="branchSort shou"
                  src="@/assets/images/disciplineGroup/up.png"
                  alt=""
                />
                <img
                  @click="branchSort(item, index, 'up')"
                  class="branchSortHover shou"
                  src="@/assets/images/disciplineGroup/uphover.png"
                  alt=""
                />
              </div>
              <div class="down" v-if="index != tableData.length - 1">
                <img
                  @click="branchSort(item, index, 'down')"
                  class="branchSort shou"
                  src="@/assets/images/disciplineGroup/down.png"
                  alt=""
                />

                <img
                  @click="branchSort(item, index, 'down')"
                  class="branchSortHover shou"
                  src="@/assets/images/disciplineGroup/downhover.png"
                  alt=""
                />
              </div>
            </div>
            <div class="branchItem_line_btns">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handelAdd(item)"
              >
                创建学科专业组
              </el-button>
            </div>
          </div>
          <!-- 专业组列表 v-if="item.disciplineGroupList.length>0"-->
          <div class="disciplineGroupList flex" v-if="item.disciplineGroupList.length > 0">
            <div
              class="disciplineGroupItem shou"
              @click="to(disciplineGroup)"
              v-for="(
                disciplineGroup, disciplineGroupIndex
              ) in item.disciplineGroupList"
              :key="disciplineGroupIndex"
            >
              <!-- 第一行 -->
              <div class="disciplineGroupItem_line1 flexBet">
                <div class="disciplineGroupItem_line1_left flexColCenter">
                  <img
                    class="disciplineGroupItem_line1_icon"
                    src="@/assets/images/disciplineGroup/disciplineGroup.png"
                    alt=""
                  />
                  <tooltip
                    width="208"
                    class="disciplineGroupItem_line1_name"
                    :text="disciplineGroup.disciplineGroupName"
                  ></tooltip>
                </div>
                <div class="disciplineGroupItem_line1_right flexColCenter">
                  <div @click.stop="">
                    <el-switch
                      size="mini"
                      @change="disciplineGroupSwitch($event, disciplineGroup)"
                      v-model="disciplineGroup.status"
                      :active-value="0"
                      :inactive-value="1"
                      active-color="#28b28b"
                      inactive-color="#d1d1d1"
                    >
                    </el-switch>
                  </div>

                  <!-- 更多 -->
                  <el-popover
                    style="height: 22px"
                    placement="bottom"
                    trigger="click"
                    :ref="`popoverName${disciplineGroup.disciplineGroupId}`"
                  >
                    <!-- 页面内容 -->
                    <img
                      @click.stop=""
                      class="disciplineGroupItem_line1_img_more shou"
                      src="@/assets/images/disciplineGroup/more.png"
                      slot="reference"
                      alt=""
                    />
                    <!-- 激活内容 -->
                    <div class="hideContent">
                      <div
                        class="flex ctemp shou"
                        @click="
                          handelEdit(disciplineGroup, disciplineGroupIndex)
                        "
                      >
                        <img
                          src="@/assets/images/disciplineGroup/edit.png"
                          alt=""
                        />编辑
                      </div>
                      <div
                        v-if="$store.getters.curRole == 'schoolAdmin'"
                        class="flex ctemp shou"
                        @click="
                          handelTop(item, disciplineGroup, disciplineGroupIndex)
                        "
                      >
                        <img
                          src="@/assets/images/disciplineGroup/top.png"
                          alt=""
                        />置顶
                      </div>
                      <div
                        v-if="disciplineGroup.status == 1"
                        class="flex ctemp shou"
                        @click="
                          handelDel(disciplineGroup, disciplineGroupIndex)
                        "
                      >
                        <img
                          src="@/assets/images/disciplineGroup/delete.png"
                          alt=""
                        />删除
                      </div>
                    </div>
                  </el-popover>
                </div>
              </div>
              <!-- 第二行 -->
              <div class="disciplineGroupItem_line2 flexColCenter">
                <img
                  class="itemIcon"
                  src="@/assets/images/disciplineGroup/leader.png"
                  alt=""
                />
                <div class="itemLabel">组长</div>
                <tooltip
                  class="itemName"
                  width="98"
                  :text="disciplineGroup.leaderName"
                ></tooltip>
                <img
                  class="itemIcon"
                  src="@/assets/images/disciplineGroup/user.png"
                  alt=""
                />
                <div class="itemLabel">组员</div>
                <div class="itemName">
                  {{
                    disciplineGroup.teacherNum ? disciplineGroup.teacherNum : 0
                  }}人
                </div>
              </div>
              <!-- 第三行 -->
              <div class="disciplineGroupItem_line2 flexColCenter">
                <img
                  class="itemIcon"
                  src="@/assets/images/disciplineGroup/file.png"
                  alt=""
                />
                <div class="itemLabel">文件</div>
                <div class="itemName">
                  {{ disciplineGroup.fileNum ? disciplineGroup.fileNum : 0 }}个
                </div>
                <img
                  class="itemIcon"
                  src="@/assets/images/disciplineGroup/course.png"
                  alt=""
                />
                <div class="itemLabel">课程</div>
                <div class="itemName">
                  {{
                    disciplineGroup.courseNum ? disciplineGroup.courseNum : 0
                  }}门
                </div>
              </div>
              <!-- 第四行 -->
              <div class="disciplineGroupItem_line2 flexColCenter">
                <img
                  class="itemIcon"
                  src="@/assets/images/disciplineGroup/branch.png"
                  alt=""
                />
                <div class="itemLabel">分院</div>
                <div class="itemNameplus">{{ disciplineGroup.branchName }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 暂无数据 -->
      <div v-else>
        <el-empty description="暂无数据~"></el-empty>
      </div>
    </div>
    <!-- 添加 -->
    <addDisciplineGroupDialog
      :open.sync="add_open"
      :type="add_type"
      :id="add_id"
      :branch="add_branch"
      @refresh="addReturn"
      @refreshCommon="getList"
    ></addDisciplineGroupDialog>
    <!-- 审核 -->
    <audit
      :open.sync="audit_open"
      :disciplineGroup="audit_disciplineGroup"
      :isSetting="audit_isSetting"
      :title="audit_title"
      @refresh="fuSwitch"
    >
    </audit>
  </div>
</template>
<script>
import audit from './components/audit.vue'
import addDisciplineGroupDialog from './components/addDisciplineGroupDialog.vue'
import {
  disciplineGroup_changeStatus,
  branchDisciplineList,
  disciplineGroup_onOffStatus,
  disciplineGroup_sortByBranch,
  disciplineGroup_sort,
  disciplineGroup_delete
} from '@/api/disciplineGroup/disciplineGroup'

export default {
  name: 'groupAdmin',
  components: { addDisciplineGroupDialog, audit },
  data() {
    return {
      audit_disciplineGroup: {},
      audit_isSetting: false,
      audit_switch: false,
      audit_title: '启用确认',
      audit_open: false,
      add_type: 'add',
      add_open: false,
      add_id: '',
      add_branch: {},
      loading: true,
      value: 1,
      tableData: [],
      params: {
        disciplineGroupName: ''
      }
    }
  },
  mounted() {
    // 获取列表
    this.getList()
    this.getSwitch()
  },
  methods: {
    // 置顶
    async handelTop(item, disciplineGroup) {
      // 要置顶的对象的 id
      const targetId = disciplineGroup.disciplineGroupId
      // 找到目标对象
      const targetObject = item.disciplineGroupList.find(
        (item) => item.disciplineGroupId === targetId
      )

      if (targetObject) {
        // 过滤掉目标对象，生成新的数组
        const remainingArray = item.disciplineGroupList.filter(
          (item) => item.disciplineGroupId !== targetId
        )

        // 将目标对象置顶
        item.disciplineGroupList = [targetObject, ...remainingArray]
        try {
          this.loading = true
          item.disciplineGroupList.map((item, index) => {
            item.sort = index
          })
          let res = await disciplineGroup_sort({
            disciplineGroupList: item.disciplineGroupList
          })
          if (res.code == 200) {
            // 遍历 this.$refs 并调用 doClose() 方法
            for (const key in this.$refs) {
              if (this.$refs.hasOwnProperty(key)) {
                const ref = this.$refs[key]

                // 判断是否是数组（当 ref 是 v-for 渲染的多个元素时）
                if (Array.isArray(ref)) {
                  ref.forEach((item) => {
                    if (item && typeof item.doClose === 'function') {
                      item.doClose()
                    }
                  })
                } else {
                  // 单个 ref 的情况
                  if (ref && typeof ref.doClose === 'function') {
                    ref.doClose()
                  }
                }
              }
            }

            this.$message({
              type: 'success',
              message: '置顶成功'
            })
          }
        } finally {
          this.loading = false
        }
      }
    },
    // 编辑
    async handelEdit(disciplineGroup) {
      this.add_branch = {
        branchId: disciplineGroup.branchId,
        branchName: disciplineGroup.branchName
      }
      this.add_id = disciplineGroup.disciplineGroupId
      this.add_open = true
      this.add_type = 'edit'
    },
    // 删除
    async handelDel(disciplineGroup) {
      this.$confirm('删除后不可恢复，请谨慎处理！', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          let res = await disciplineGroup_delete(
            disciplineGroup.disciplineGroupId
          )
          const { code } = res
          if (code == 200) {
            this.$modal.msgSuccess('删除成功!')
            this.getList()
          }
        })
        .catch(() => {
          this.$modal.msgInfo('已取消')
        })
    },
    // 学科专业组功能开启关闭
    async fuSwitch(e) {
      // 学科专业组功能开启关闭 1是启用 0是关闭
      if (e.isSetting) {
        this.value = e.status
      }
      // 学科专业组的状态 1是关闭 0是启用
      else {
        this.audit_disciplineGroup.status = e.status
      }
    },
    // 专业组开关
    async disciplineGroupSwitchFn(e, disciplineGroup) {
      try {
        this.loading = true
        let res = await disciplineGroup_changeStatus({
          disciplineGroupId: disciplineGroup.disciplineGroupId,
          status: e
        })
        if (res.code == 200) {
          this.$modal.msgSuccess(`${e == 0 ? '启用成功' : '停用成功'}`)
        } else {
          disciplineGroup.status = e == 1 ? 0 : 1
        }
      } finally {
        this.loading = false
      }
    },
    disciplineGroupSwitch(e, disciplineGroup) {
      if (e == 0) {
        this.$confirm('启用后课程可选择该学科专业组', '启用确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.disciplineGroupSwitchFn(e, disciplineGroup)
          })
          .catch(() => {
            this.$modal.msgInfo('已取消')
            disciplineGroup.status = e == 1 ? 0 : 1
          })
      } else {
        this.audit_disciplineGroup = disciplineGroup
        this.audit_isSetting = false
        this.audit_title = e == 0 ? '启用确认' : '停用确认'
        this.audit_open = true
      }
    },
    // 分院上移下移
    async branchSort(item, index, type) {
      let arr = JSON.parse(JSON.stringify(this.tableData))
      if (type == 'up') {
        arr.splice(index - 1, 0, arr.splice(index, 1)[0])
      } else {
        arr.splice(index + 1, 0, arr.splice(index, 1)[0])
      }
      arr.map((item, index) => {
        arr[index].sort = index + 1
        delete arr[index].disciplineGroupList
        delete arr[index].branchName
      })
      try {
        this.loading = true
        let res = await disciplineGroup_sortByBranch({
          disciplineGroupList: arr
        })
        if (res.code == 200) {
          this.$modal.msgSuccess(`${type == 'up' ? '上移成功' : '下移成功'}`)
          if (type == 'up') {
            this.tableData.splice(
              index - 1,
              0,
              this.tableData.splice(index, 1)[0]
            )
          } else {
            this.tableData.splice(
              index + 1,
              0,
              this.tableData.splice(index, 1)[0]
            )
          }
        }
      } finally {
        this.loading = false
      }
    },
    // 获取学科专业组开关状态
    async getSwitch() {
      try {
        let res = await disciplineGroup_onOffStatus()
        if (res.code == 200) {
          this.value = res.data.onOffStatus
          console.log(this.value)
        }
      } finally {
      }
    },

    async switchChange(e) {
      console.log(e)
      if (e == 1) {
        let num = 0
        this.tableData.map((item) => {
          item.disciplineGroupList.map((item) => {
            if (item.status == 0) {
              num++
            }
          })
        })
        if (num == 0) {
          this.$message({
            type: 'warning',
            message: '请先创建（并启用）学科专业组'
          })
          this.value = 0
          return false
        }
      }
      this.audit_isSetting = true
      this.audit_title = e == 1 ? '启用确认' : '停用确认'
      this.audit_open = true
    },
    handelAdd(item) {
      this.add_branch = item
      this.add_id = ''
      this.add_open = true
      this.add_type = 'add'
    },
    resetSearch() {
      this.params = {
        disciplineGroupName: ''
      }
      this.getList()
    },
    addReturn(id) {
      // this.$modal.msgSuccess("新增成功");
      this.$confirm('启用后课程可选择该学科专业组', '启用确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await this.disciplineGroupSwitchFn(0, id)
          this.add_open = false
          this.getList()
        })
        .catch(() => {
          this.$modal.msgInfo('已取消')
          this.getList()
        })
    },
    async getList() {
      try {
        this.params.schoolId = this.$store.getters.schoolId
        if (this.$store.getters.curRole == 'branchAdmin') {
          this.params.branchId = this.$store.getters.branchId
        }

        let res = await branchDisciplineList(this.params)
        if (res.code == 200) {
          this.tableData = res.data
        }
      } finally {
        this.loading = false
      }
    },
    to(item) {
      this.$router.push({
        path: '/schoolOrganization/disciplineGroupDetail',
        query: {
          disciplineGroupId: item.disciplineGroupId,
          disciplineGroupName: item.disciplineGroupName,
          branchName: item.branchName
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.hideContent {
  img {
    margin: auto 17px auto 20px;
    width: 15px;
    height: 15px;
  }

  .ctemp {
    padding-right: 32px;
    box-sizing: border-box;
    font-size: 14px;
    color: #666666;
    line-height: 36px;
    height: 36px;
    border-bottom: 1px solid #edeff0;
  }

  .ctemp:hover {
    background: #f5f5f5;
  }
}

::v-deep .el-button--success {
  background-color: #5a9cf8;
  border: 1px solid #5a9cf8;
}

::v-deep .el-button--success.is-disabled {
  background-color: #aacefb;
  border: 1px solid #aacefb;
}

.container {
  background: #f3f4f6;
  padding: 20px;
  box-sizing: border-box;
  height: calc(100vh - 84px);

  .card {
    display: flex;
    flex-direction: column;
    background: #ffffff;
    height: calc(100vh - 124px);
    box-shadow: 0 0 10px 0 rgba(0, 74, 88, 0.06);
    border-radius: 16px;
    padding: 38px 0 24px 24px;
    box-sizing: border-box;

    .list {
      box-sizing: border-box;
      padding-right: 24px;
      flex: 1 auto;
      overflow-y: auto;
      margin-top: 31px;

      .branchItem {
        margin-bottom: 32px;

        .branchItem_line {
          .up {
            .branchSort {
              display: block;
            }

            .branchSortHover {
              display: none;
            }
          }

          .up:hover {
            .branchSort {
              display: none;
            }

            .branchSortHover {
              display: block;
            }
          }

          .down {
            .branchSort {
              display: block;
            }

            .branchSortHover {
              display: none;
            }
          }

          .down:hover {
            .branchSort {
              display: none;
            }

            .branchSortHover {
              display: block;
            }
          }

          .branchName {
            font-family: PingFangSC, PingFang SC, sans-serif;
            font-weight: 500;
            font-size: 18px;
            color: #333333;
            line-height: 25px;
            text-align: left;
            font-style: normal;
            margin-right: 8px;

            .branchSort {
              margin-left: 16px;
              width: 20px;
              height: 20px;
            }

            .branchSortHover {
              margin-left: 16px;
              width: 20px;
              height: 20px;
            }
          }

          .branchItem_line_btns {
          }
        }

        .disciplineGroupList {
          .disciplineGroupItem {
            width: 352px;
            height: 166px;
            background: #ffffff;
            border-radius: 12px;
            border: 1px solid #ebebeb;
            margin: 20px 10px 0 10px;

            .disciplineGroupItem_line1 {
              margin-bottom: 23px;
              padding: 20px 11px 0 18px;

              ::v-deep .el-switch {
                // 缩小
                transform: scale(0.8);
              }

              .disciplineGroupItem_line1_left {
                .disciplineGroupItem_line1_icon {
                  width: 24px;
                  height: 24px;
                  margin-right: 8px;
                }

                .disciplineGroupItem_line1_name {
                  width: 208px;
                  font-family: PingFangSC, PingFang SC, sans-serif;
                  font-weight: 500;
                  font-size: 16px;
                  color: #333333;
                  line-height: 18px;
                  text-align: left;
                  font-style: normal;
                }
              }

              .disciplineGroupItem_line1_right {
                .disciplineGroupItem_line1_img_more {
                  width: 20px;
                  height: 20px;
                  margin-left: 12rpx;
                }
              }
            }

            .disciplineGroupItem_line2 {
              margin-bottom: 8px;
              padding: 0 0 0 27px;

              .itemIcon {
                width: 16px;
                height: 16px;
                margin-right: 3px;
              }

              .itemLabel {
                font-family: PingFangSC, PingFang SC, sans-serif;
                font-weight: 400;
                font-size: 14px;
                color: #99a1b3;
                line-height: 22px;
                text-align: left;
                font-style: normal;
                margin-right: 8px;
              }

              .itemName {
                width: 98px;
                font-family: PingFangSC, PingFang SC, sans-serif;
                font-weight: 400;
                font-size: 14px;
                color: #333333;
                line-height: 22px;
                text-align: left;
                font-style: normal;
              }

              .itemNameplus {
                font-family: PingFangSC, PingFang SC, sans-serif;
                font-weight: 400;
                font-size: 14px;
                color: #333333;
                line-height: 22px;
                text-align: left;
                font-style: normal;
              }
            }
          }
        }
      }
    }

    .switchLine {
      margin-bottom: 21px;

      .switchLine_left {
        margin-right: 10px;
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 500;
        font-size: 16px;
        color: #333333;
        line-height: 22px;
        text-align: left;
        font-style: normal;
      }

      .switchLine_right {
        margin-left: 32px;
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 16px;
        color: #f89a33;
        line-height: 22px;
        text-align: left;
        font-style: normal;
      }
    }
  }

  .search_bar {
    box-sizing: border-box;
    width: auto !important;
    height: 80px !important;
    margin-right: 24px;
    padding: 18px 20px 0 32px;
    background-color: #fafafa;
    border-radius: 8px;

    .search_btns {
      float: right;
    }
  }

  .btns {
    margin: 20px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .progress_info {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
